package com.zqs.compareface.server.camstream;

import com.zqs.compareface.controller.StreamController;
import com.zqs.compareface.dao.UserData;
import com.zqs.compareface.dao.UserFaceData;
import com.zqs.compareface.entity.UserImage;
import com.zqs.compareface.myenum.Judges;
import com.zqs.compareface.server.apiserver.BaiduApiJudge;
import com.zqs.compareface.utils.impl.ImageToBase64Util;
import com.zqs.compareface.utils.impl.ResultUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.FrameGrabber;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.json.JSONObject;

import java.awt.image.BufferedImage;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Program: face
 * @Description:
 * @Author: zqs
 * @Create： 2021-08-10-15:57
 */
public class CamStreamPullScreenShotsThread extends Thread {
    protected final Log log = LogFactory.getLog(getClass());
    private String streamURL = StreamController.STREAM_URL;// 流地址
    private String outputFile;// 文件路径
    private BaiduApiJudge baiduApiJudge;

    public CamStreamPullScreenShotsThread(BaiduApiJudge baiduApiJudge) {
        this.baiduApiJudge = baiduApiJudge;
    }

    public void setStreamURL(String streamURL) {
        this.streamURL = streamURL;
    }

    public void setOutputFile(String outputFile) {
        this.outputFile = outputFile;
    }
    public void pullStart(){
        start();
    }

    @Override
    public void run(){
        Date nowTime = new Date(System.currentTimeMillis());
        SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

        //获取视频源
        FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(streamURL);
        grabber.setImageWidth(640);
        grabber.setImageHeight(480);
        //开始获取视频数据
        try{
            grabber.start();
        }catch (Exception e){
            try {
                //一次重启尝试
                grabber.start();
            }catch (Exception e2){
                try {
                    throw e;
                } catch (FFmpegFrameGrabber.Exception exception) {
                    exception.printStackTrace();
                }
            }
        }
        try {
            String base64CodeImage = null;
            while (grabber != null){
                System.out.println(sdFormatter.format(System.currentTimeMillis()));
                Frame videoPic = grabber.grabImage();
                if(videoPic!=null){
                    //TODO 改为多线程提交图片做Base64处理，并放入集合中排队提交检测
                    /**
                     * 转为BufferedImage类型
                     */
                    BufferedImage bufferedImage = new Java2DFrameConverter().getBufferedImage(videoPic);
                    /**
                     * 通过Util工具转码为base64
                     */
//                    ImageToBase64Util.convertBase64(bufferedImage);
                    /**
                     * 直接提交到百度API检测
                     */
//                    commitToBaiduApi.commitToBaiduApi(ImageToBase64Util.convertBase64(bufferedImage));
                    String imageTypes = "BASE64";
                    UserImage userImage = new UserImage("wuyifang","user",ImageToBase64Util.convertBase64(bufferedImage));
                    UserData userData = new UserFaceData(userImage);
                    //做了线程同步（处理能力原因）直接调用本类中的API实列，不需要再new
//                    BaiduApiJudge baiduApiJudge = new BaiduApiJudge();
                    JSONObject result = BaiduApiJudge.faceToFaceCompare(userData, imageTypes);
                    Boolean compareResult = ResultUtil.isOrNot(result);
                    if (!compareResult){
                        log.info(Judges.ISNOT.getJudges());
                    }else {
                        log.info(Judges.IS.getJudges());
                    }
                    Thread.sleep(50);
                    log.info("图片已提交转码 wait.....");
                }
            }
            grabber.stop();
        } catch (FFmpegFrameGrabber.Exception | InterruptedException e) {
            e.printStackTrace();
        } finally {
                try {
                    grabber.close();
                } catch (FrameGrabber.Exception e) {
                    e.printStackTrace();
                }
        }
    }

    public static void main(String[] args) {
        /**
         * 并发线程，main主线程和新建的t线程，共同执行任务
         * 多个线程就new多个Thread
         * 线程同步加锁到要同步的那个实列类上或方法区中，并在当前类中引入那个实列类
         * 新建的线程需要将加锁的那个实列加入当前类的构造中
         */
        BaiduApiJudge baiduApiJudge = new BaiduApiJudge();
        Thread t = new CamStreamPullScreenShotsThread(baiduApiJudge);
        t.start();
    }
}
